<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户设置</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <hr />

    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            v-model="queryInfo.tecName"
            placeholder="请输入姓名"
            clearable
            @clear="getUserList"
            @change="getUserList"
          >
            <template slot="prepend">姓名</template>
          </el-input>
        </el-col>

        <el-col :span="7">
          <el-input
            v-model="queryInfo.tecUser"
            placeholder="请输入用户名"
            clearable
            @clear="getUserList"
            @change="getUserList"
          >
            <template slot="prepend">用户名</template>
          </el-input>
        </el-col>

        <el-col :span="3">
          <el-button type="primary" @click="getUserList">查询</el-button>
        </el-col>
      </el-row>

      <!-- 功能区域 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column
          type="index"
          label="用户编号"
          width="100px"
        ></el-table-column>
        <el-table-column prop="tecName" label="姓名" sortable></el-table-column>
        <el-table-column prop="tecUser" label="用户名"></el-table-column>
        <el-table-column
          prop="dataScope"
          label="权限角色"
          width="100px"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.eduRole.dataScope == '1'"
              >超级管理员</el-tag
            >
            <el-tag
              type="warning"
              v-else-if="scope.row.eduRole.dataScope == '2'"
              >教师管理员</el-tag
            >
            <el-tag type="info" v-else-if="scope.row.eduRole.dataScope == '3'"
              >教师</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              plain
              @click="showEditDialog(scope.row.tecId)"
              >编辑</el-button
            >

            <!-- 分配权限 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              plain
              @click="showSetEditDialog(scope.row)"
              >分配</el-button
            >

            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              plain
              @click="removeDialog(scope.row.tecId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.page"
        :page-size="queryInfo.size"
        layout="total, prev, pager, next"
        :total="totalPage"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @open="getRoles"
      @close="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="110px"
      >
        <el-form-item label="姓名" prop="tecName">
          <el-input v-model="addForm.tecName"></el-input>
        </el-form-item>

        <el-form-item label="身份证" prop="tecPerId">
          <el-input v-model="addForm.tecPerId"></el-input>
        </el-form-item>

        <el-form-item label="用户名" prop="tecUser">
          <el-input v-model="addForm.tecUser"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="tecPwd">
          <el-input v-model="addForm.tecPwd" show-password></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="tecRePwd">
          <el-input v-model="addForm.tecRePwd" show-password></el-input>
        </el-form-item>

        <el-form-item label="角色权限设置" prop="roleId">
          <el-select v-model="addForm.roleId" placeholder="请选择权限">
            <el-option
              v-for="role in roles"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="width"
      @close="editDialogClose"
    >
      <!-- 内容主体区域 -->
      <el-form
        ref="editFormRef"
        :rules="editFormRules"
        :model="editForm"
        label-width="110px"
      >
        <el-form-item label="姓名" prop="tecName">
          <el-input v-model="editForm.tecName" disabled></el-input>
        </el-form-item>

        <el-form-item label="身份证" prop="tecPerId">
          <el-input v-model="editForm.tecPerId" disabled></el-input>
        </el-form-item>

        <el-form-item label="用户名" prop="tecUser">
          <el-input v-model="editForm.tecUser"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            icon="el-icon-refresh-left"
            plain
            @click="reDialogVisible = true"
            >重置密码</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRole">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码警告框 -->
    <el-dialog title="警告" :visible.sync="reDialogVisible" width="30%">
      <span>您确定要重置密码吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="reDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetPwd()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限框 -->
    <el-dialog title="分配权限" :visible.sync="setDialogVisible" width="width">
      <el-row :gutter="10">
        <el-col :span="4">设置权限</el-col>
        <el-col :span="6">
          <el-select v-model="setRole.roleId" placeholder="请选择权限">
            <el-option
              :key="role.roleId"
              v-for="role in roles"
              :label="role.roleName"
              :value="role.roleId"
            ></el-option>
          </el-select>
        </el-col>
      </el-row>

      <div slot="footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setPower">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除警告框 -->
    <el-dialog title="警告" :visible.sync="delDialogVisible" width="30%">
      <span>您确定要删除此用户吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="delById">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证身份证号
    var checkTecPerId = (rule, value, cb) => {
      const reg = /^[0-9]{18}$/
      if (reg.test(value)) {
        return cb()
      }
      cb(new Error('身份证号输入有误'))
    }

    // 验证密码长度
    var checkPwd = (rule, value, cb) => {
      if (value.toString().length < 6 || value.toString().length > 18) {
        cb(new Error('密码长度为6 - 18个字符'))
      }
      return cb()
    }

    // 验证两次输入是否一样
    var checkRePwd = (rule, value, cb) => {
      if (this.addForm.tecPwd !== this.addForm.tecRePwd) {
        cb(new Error('两次输入的密码不相同'))
      }
      return cb()
    }

    return {
      userList: [],
      queryInfo: {
        page: 1,
        size: 10,
        tecName: '',
        tecUser: ''
      },
      totalPage: 0,
      addDialogVisible: false,
      addForm: {
        tecName: '',
        tecPerId: '',
        tecUser: '',
        tecPwd: '',
        tecRePwd: '',
        roleId: ''
      },
      roles: [],
      addFormRules: {
        tecName: [
          {
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }
        ],
        tecPerId: [
          {
            required: true,
            message: '请输入身份证',
            trigger: 'blur'
          },
          {
            validator: checkTecPerId,
            trigger: 'blur'
          }
        ],
        tecUser: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ],
        tecPwd: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            validator: checkPwd,
            trigger: 'blur'
          }
        ],
        tecRePwd: [
          {
            required: true,
            message: '请再次输入密码',
            trigger: 'blur'
          },
          {
            validator: checkRePwd,
            trigger: 'blur'
          }
        ],
        roleId: [
          {
            required: true,
            message: '请选择权限',
            trigger: 'blur'
          }
        ]
      },
      editDialogVisible: false,
      editForm: [],
      editFormRules: {
        tecUser: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }
        ]
      },
      reDialogVisible: false,
      setDialogVisible: false,
      setRole: {
        tecId: 0,
        roleId: '',
        updateBy: ''
      },
      delDialogVisible: false
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('role/list', {
        params: this.queryInfo
      })
      if (res.code !== 20000) {
        return this.$message.error('查询用户列表失败!')
      }
      this.userList = res.data.list
      this.totalPage = res.data.total
    },
    async getRoles() {
      const { data: res } = await this.$http.get('role/all')
      if (res.code !== 20000) {
        return this.$message.error('查询权限列表失败!')
      }
      this.roles = res.data
    },
    handleCurrentChange(newPage) {
      this.queryInfo.page = newPage
      this.getUserList()
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    addRole() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        this.addForm.updateBy = window.sessionStorage.getItem('rootname')
        const { data: res } = await this.$http.post('role/add', this.addForm)
        if (res.code === 20005) return this.$message.error('重复操作!')
        else if (res.code === 20006) {
          return this.$message.error('未找到教师信息!')
        } else if (res.code === 20007) {
          return this.$message.error('用户名重复!')
        } else if (res.code === 20000) {
          this.addDialogVisible = false
          this.getUserList()
          return this.$message.success('添加成功')
        }
      })
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('role/one/' + id)
      if (res.code !== 20000) {
        return this.$message.error('查询出错啦~')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    async resetPwd() {
      const { data: res } = await this.$http.put(
        'role/reset/' + this.editForm.tecId
      )
      if (res.code !== 20000) {
        return this.$message.error('无法完成重置密码任务!')
      }
      this.reDialogVisible = false
      return this.$message.success('成功重置! ')
    },
    updateRole() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        this.editForm.updateBy = window.sessionStorage.getItem('rootname')
        const { data: res } = await this.$http.put('role/update', this.editForm)
        if (res.code !== 20000) {
          return this.$message.error('更新失败!')
        }
        this.getUserList()
        this.editDialogVisible = false
        return this.$message.success('修改成功!')
      })
    },
    showSetEditDialog(role) {
      this.getRoles()
      this.setRole.tecId = role.tecId
      this.setRole.roleId = role.roleId
      this.setDialogVisible = true
    },
    async setPower() {
      this.setRole.updateBy = window.sessionStorage.getItem('rootname')
      const { data: res } = await this.$http.put('role/power', this.setRole)
      if (res.code !== 20000) {
        return this.$message.error('无法完成权限分配!')
      }
      this.getUserList()
      this.setDialogVisible = false
      return this.$message.success('分配成功!')
    },
    removeDialog(id) {
      this.setRole.tecId = id
      this.delDialogVisible = true
    },
    async delById() {
      this.setRole.updateBy = window.sessionStorage.getItem('rootname')
      const { data: res } = await this.$http.put('role/del', this.setRole)
      if (res.code !== 20000) {
        return this.$message.error('无法删除该用户!')
      }
      this.getUserList()
      this.delDialogVisible = false
      return this.$message.success('删除成功!')
    }
  }
}
</script>

<style>
.el-col {
  line-height: 40px;
}

.el-row {
  margin-bottom: 10px;
  text-align: left;
}

.el-form-item {
  text-align: left;
}
</style>
